#ifndef __MY_EPOLL__
#define __MY_EPOLL__

#include <iostream>
#include <sys/epoll.h>
#include <fcntl.h>
#include <unistd.h>
#include "ConnectData.hpp"
#include <cstring>

class MyEpoll
{
public:
    static bool EnableReadWrite(ConnectData *con, bool read, bool write);
   
    static int CreateEpoll()
    {
        int ret = epoll_create1(EPOLL_CLOEXEC);
        if (ret == -1)
        {
            FAIL("epoll_create fail %s", strerror(errno));
            exit(3);
        }
        return ret;
    }

    static bool CtlEpoll(int efd, int fd, int op, uint32_t event)
    {
        epoll_event tmp;
        tmp.data.fd = fd;
        tmp.events = event;

        if (epoll_ctl(efd, op, fd, &tmp) == -1)
        {
            FAIL("epoll_ctl fail %s", strerror(errno));
            exit(3);
        }
        return true;
    }

    static int WaitEpoll(int efd, struct epoll_event revents[], size_t num, int timeout)
    {
        int ret = epoll_wait(efd, revents, num, timeout);
        if (ret == -1)
        {
            FAIL("epoll_wait fail %s", strerror(errno));
            exit(3);
        }
        return ret;
    }

    static int DelEpoll(int efd, int fd)
    {
        int ret = epoll_ctl(efd, EPOLL_CTL_DEL, fd, nullptr);
        if (ret == -1)
        {
            FAIL("epoll_wait fail %s", strerror(errno));
            exit(3);
        }
        return ret;
    }

    static int SetSocketNoHang(int socket)
    {
        int tmp = fcntl(socket, F_GETFL);
        if (tmp == -1)
            return -1;
        fcntl(socket, F_SETFL, tmp | O_NONBLOCK);
        return 0;
    }
};

#endif
